<template>
  <div>
    <el-card>
    <div>
      <el-button
        type="danger"
        :disabled="ids.length === 0"
        @click="deleteClick()"
        v-hasPerm="['sys:sensitiveWord:del']"
        ><i-ep-delete />删除</el-button
      >

      <el-button type="success"  v-hasPerm="['sys:sensitiveWord:add']" @click="addClick()" plain>添加敏感词</el-button>
    </div>
  </el-card>

  <el-card>
    <el-table
      :data="tableData"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" align="center" />
      <!-- <el-table-column prop="id" label="序号" width="120" /> -->
			<el-table-column
                fixed
                type="index"
                :index="indexMethod"
                label="序号"
                width="70"
              />
      <el-table-column prop="word" label="敏感词" width="320" />
      <el-table-column prop="createTime" label="创建时间" width="400" />
      <el-table-column prop="founder" label="添加用户" width="120" />

      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button type="warning" @click="modifyClick(scope.row)"  v-hasPerm="['sys:sensitiveWord:update']"
            >修改</el-button
          >
          <el-button type="danger" @click="deleteClick(scope.row.id)"  v-hasPerm="['sys:sensitiveWord:del']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页搜索 -->
    <div
      style="
        display: flex;
        justify-content: center;
        width: 100%;
        margin-top: 15px;
      "
    >
      <el-pagination
        background
        layout="sizes, prev,slot, next, jumper"
        :page-count="pageTotal"
        :page-sizes="[10, 20, 30, 50]"
        :current-page="activePager"
        @update:current-page="pageChange"
        @update:page-size="sizeChange"
        :default-current-page="1"
        :default-page-size="10"
      >
        <div class="pagination">
          <span
            class="pagination__item"
            :class="{ active: activePager === pager }"
            v-for="pager in pageArr"
            :key="pager"
            @click="pageChange(pager)"
          >
            {{ pager }}
          </span>
        </div>
      </el-pagination>
    </div>
    <!-- 分页搜索 -->
  </el-card>

  <el-dialog v-model="dialogEdit" title="Shipping address">
    <el-form label-width="100px" :model="editList" style="max-width: 460px">
      <el-form-item label="序号">
        <el-input v-model="editList.id" disabled/>
      </el-form-item>
      <el-form-item label="敏感词">
        <el-input v-model="editList.word" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input v-model="editList.createTime" disabled/>
      </el-form-item>
      <el-form-item label="管理员">
        <el-input v-model="editList.founder" disabled/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEdit = false">取消</el-button>
        <el-button type="primary" @click="dialogEditForm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogAdd" title="请输入你要添加的敏感词">
    <el-form
      label-width="100px"
      :model="addList"
      ref="addFormRef"
      :rules="rules"
      style="max-width: 460px"
    >
      <el-form-item label="敏感词" prop="word">
        <el-input v-model="addList.word" placeholder="请输入你要添加的敏感词" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAdd = false">取消</el-button>
        <el-button type="primary" @click="dialogAddForm(addFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { sensitiveList, parameter } from "../../../api/sensitive/type";
import { onMounted, reactive, ref } from "vue";
import {
  getSensitiveList,
  deleteSensitive,
  editSensitive,
  addSensitive,
} from "../../../api/sensitive/index";

const loading = ref(false);

let tableData = ref<sensitiveList[]>();
const dialogEdit = ref(false);

//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

const dialogAdd = ref(false);

const ids = ref([]);

import type { FormInstance, FormRules } from "element-plus";

const addFormRef = ref<FormInstance>();

let editList = reactive<sensitiveList>({
  id: 0,
  word: "",
  createTime: "",
  founder: "",
});

let keys = reactive<parameter>({
  pageNum: 1,
  pageSize: 10,
});


const indexMethod = (index: number) => {
  return index + 10 * activePager.value - 9;
};


let addList = reactive<sensitiveList>({
  word: "",
});

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the word"));
  } else {
    if (addList.word !== "") {
      if (!addFormRef.value) return;
      addFormRef.value.validateField("word", () => null);
    }
    callback();
  }
};

const rules = reactive<FormRules>({
  word: [{ validator: validatePass, trigger: "blur" }],
});

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 编辑
 */
async function modifyClick(row: sensitiveList) {
  dialogEdit.value = true;
  await Object.assign(editList, row);
}

async function dialogEditForm() {
  await editSensitive(editList).then(({ data }) => {
    ElMessage.success("修改成功");
    dialogEdit.value = false;
    resetSensitive();
  });
}

/**
 * 删除
 */

async function deleteClick(id?: number) {
  const adminIds = [id || ids.value] as number[];
  await ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteSensitive(adminIds).then(() => {
      ElMessage.success("删除成功");
      resetSensitive();
    });
  });
}

/**
 * 添加
 */

function addClick() {
  dialogAdd.value = true;
}

const dialogAddForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      addSensitive(addList)
        .then(() => {
          ElMessage.success("添加成功");
          resetSensitive();
          dialogAdd.value = false;
        })
        .finally(() => (loading.value = false));
    }
  });
};

/**
 * 刷新
 */
function resetSensitive() {
  handleData();
}

/**
 * 获取敏感词列表
 */
async function handleData() {
  loading.value = true;
  await getSensitiveList(keys)
    .then(({ data }) => {
      tableData.value = data.sensitiveWords;
      pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
      pageArr.value = data.navigatepageNums;
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

function pageChange(pageNum: number) {
  keys.pageNum = pageNum;
  activePager.value = pageNum;
  handleData();
}

function sizeChange(sizeNum: number) {
  keys.pageSize = sizeNum;
  handleData();
}

onMounted(() => {
  handleData();
});
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}
</style>
